<?php
class NX_Log{
	protected static $_instance = null;
	public $_prefixInfo = '';
	public $_logArr = array();				// LOG缓存区
	public $_path = null;
	public $_pathType = 'd';
	public $_logLevel = array('fatal'=>true,'error'=>true,'warn'=>false,'info'=>false,'debug'=>false);
	// 构造函数
	protected function __construct()
	{
	}

	// 析构函数
	public function __destruct(){
		$this->saveLogArr($this->_path,$this->_logArr);
		$this->_logArr = array();
	}

	// 设置 全局LOG对象
	public static function getLog($class){
		global $NX_Cfg;
		$log = self::getInstance($NX_Cfg['log']);
		$log->_prefixInfo = trim($class).' ';
		return $log;
	}
	
	// 得到对象
	public static function getInstance($cfg){
		// $cfg path level
		$key = serialize($cfg);
		// 生成缓存
		if(!isset(self::$_instance[$key]) || !self::$_instance[$key] instanceof self){
			self::$_instance[$key] = new self();
			self::$_instance[$key]->cfg($cfg);
		}
		// 返回缓存
		return self::$_instance[$key];
	}

	// 配置
	protected function cfg($cfg){		
		// 等级配置
		$level = explode(',',$cfg['level']);
		foreach ($level as $v){
			$this->_logLevel[$v] = true;
		}
		// 初始化 LOG目录
		if(NX_File::makeDirs(dirname($cfg['path']))){
			$pathType = strtolower($cfg['pathType']);
			if($this->_pathType == 'd'){
				$this->_path = $cfg['path'].'_'.date('Y-m-d',time()).'.log';
			}
			else if($this->_pathType == 'm'){
				$this->_path = $cfg['path'].'_'.date('Y-m',time()).'.log';
			}
			else if($this->_pathType == 'y'){
				$this->_path = $cfg['path'].'_'.date('Y',time()).'.log';
			}
			else{
				$this->_path = $cfg['path'];
			}
		}
		else {
			self::alert('make LogDir Err');
		}
	}

	public function error($info){
		$rs = $this->saveLog('error',$info);
	}

	public function debug($info){
		$rs = $this->saveLog('debug',$info);
	}

	public function info($info){
		$rs = $this->saveLog('info',$info);
	}

	public function warn($info){
		$rs = $this->saveLog('warn',$info);
	}

	public function fatal($info){
		$rs = $this->saveLog('fatal',$info);
	}

	public function saveLog($level,$info){
		//print_r(debug_backtrace());
		if(isset($this->_logLevel[$level]) && $this->_logLevel[$level]){
			$infos = $this->getInfos($level,$info);
			$this->_logArr[] = $infos;
			if(sizeof($this->_logArr)>=50){
				self::saveLogArr($this->_path,$this->_logArr);
				$this->_logArr = array();
			}
		}
		return false;
	}

	public static function saveLogArr($path,$arr){
		foreach ($arr as $r){
			NX_File::saveFile($path,$r."\r\n",'a+');
		}
	}

	public function getInfos($level,$info){
		if($this->_pathType == 'd'){
			$infos = date('H:i:s',time());
		}
		elseif($this->_pathType == 'm'){
			$infos = date('d H:i:s',time());
		}
		else{
			$infos = date('Y-m-d H:i:s',time());
		}
		$infos.=' '.$level.' '.$this->_prefixInfo.$info;
		return $infos;
	}

	public function alert($log){
		echo 'Class:NX_LOG '.$log;
		exit();
	}

	public static function log($path,$log,$type){

	}
}
?>